import { useEffect } from 'react';

import { Router } from 'next/router';

export const usePreventRedirect = (condition: boolean, callback: () => void) => {
  useEffect(() => {
    if (!condition) {
      return;
    }
    const routeChangeStart = (url: string) => {
      callback();
      Router.events.emit('routeChangeError');
      // eslint-disable-next-line @typescript-eslint/no-throw-literal
      throw `Route change to "${url}" was aborted.`;
    };
    Router.events.on('routeChangeStart', routeChangeStart);

    return () => {
      Router.events.off('routeChangeStart', routeChangeStart);
    };
  }, [condition]);
};
